package main

import (
	"cloud-native/global"
	"cloud-native/internal/middleware"
	"cloud-native/pkg/setting"
	"context"
	"errors"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func init() {
	err := setupSetting()
	if err != nil {
		log.Fatalf("init.setupSetting err := %v", err)
	}
}

func main() {

	router := gin.Default()
	router.Use(middleware.ContextTimeout(time.Second))
	router.Use(middleware.AccessLog())
	{
		router.GET("/", func(c *gin.Context) {
			//for k,v:= range c.Request.Header  {
			//	c.Writer.Header().Set(k,strings.Join(v,","))
			//}
			version := os.Getenv("VERSION")
			c.Writer.Header().Add("VERSION", version)
			data := gin.H{"msg": "hello world", "date": time.Now()}
			c.JSON(http.StatusOK, data)
		})
		router.POST("/healthz", func(c *gin.Context) {
			c.String(http.StatusOK, "hlealthz")
		})
	}

	srv := &http.Server{
		Addr:    ":" + global.ServerSetting.HttpPort,
		Handler: router,
	}

	go func() {
		if err := srv.ListenAndServe(); err != nil && errors.Is(err, http.ErrServerClosed) {
			log.Printf("listen: %s\n", err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit
	log.Println("Shutting down server...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatal("Server forced to shutdown:", err)
	}

	log.Println("Server exiting")
}

func setupSetting() error {
	setting, err := setting.NewSetting()
	if err != nil {
		return err
	}
	err = setting.ReadSection("Server", &global.ServerSetting)
	if err != nil {
		return err
	}
	return nil
}
